package net.esj.auth.inst.struts2;

import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import net.esj.auth.Constants;
import net.esj.auth.manager.AuthManager;
import net.esj.auth.pojo.CoreAdmin;
import net.esj.auth.pojo.CoreAuthFunc;
import net.esj.auth.pojo.CoreAuthModel;
import net.esj.basic.core.view.support.vojo.BaseVojo;
import net.esj.basic.core.view.support.vojo.TransObject;
import net.esj.basic.plugins.view.easyui.utils.EasyUITreeConverter;
import net.esj.basic.plugins.view.easyui.utils.EasyUITreeEntity;
import net.esj.basic.pojo.TreeStructure;
import net.esj.basic.pojo.op.Administrator;
import net.esj.basic.service.provider.UserRuleProvider;
import net.esj.basic.utils.CollectionUtils;
import net.esj.basic.utils.StringUtils;
import net.esj.basic.utils.Validators;
import net.melon.agency.inst.ssh.service.AuthService;
import net.melon.agency.pojo.AgencyUser;

public class FuncAction extends AbstractAuthAction<CoreAuthFunc, CoreAuthFunc> implements Constants{
	
	//private static Logger logger = LoggerFactory.getLogger(FuncAction.class);

	private List funcs;
	
	private List<CoreAuthModel> models;
	
	private AuthManager authManager;
	
	@Resource
	private AuthService authService;
	
	private CoreAuthModel model;
	
	private String key;
	
	private int priority;
	
	public String list(){
		if(Validators.isEmpty(key)){
			models = authManager.allModels();
			if(!CollectionUtils.isEmpty(models)){
				id = models.get(0).getId();
			}
		}else{
			id = key;
		}
		return execute();
	}
	
	@Override
	public void datagrid() {
		if(entity==null || !StringUtils.hasText(entity.getId())){
			if("CORE_ADMIN".equals(model.getId())){
				CoreAdmin admin = getSessionUser(CoreAdmin.class);
				if(admin.getName().equals(CoreAdmin.SUPER_ADMINISTRATOR_NAME)){
					funcs = authManager.findFunctions(null,model,priority,true,true);
				}else{
					funcs = authManager.findMyFunctions(admin);
				}
				
			}else{
				AgencyUser au = getSessionUser(AgencyUser.class);
				if(Validators.isEmpty(au)){
					funcs = authManager.findFunctions(null,model,priority,true,true);
				}else{
					if(au.isSuper()){
						funcs = authManager.findFunctions(null,model,priority,true,true);	
					}else{
						au = authService.getUserWithAuth(au.getId());
						funcs = au.getAllowedTree();
					}
				}
			}
		}else{
			funcs = authManager.findFunctions(entity,model,priority,true,true);
		}
		Collection<EasyUITreeEntity> tree = new FuncEasyUITreeConverter().convert(funcs);
		writeJson(tree);
	}
	
	public void mygrid(){
		Administrator admin= UserRuleProvider.getSessionUser(getSession(), model.getId());
		Collection<EasyUITreeEntity> tree = new FuncEasyUITreeConverter().convert(admin.authFunctions());
		writeJson(tree);
	}
	
	@Override
	protected boolean beforeAdd() {
		if(entity.getParent()!=null && Validators.isEmpty(entity.getParent().getId())){
			entity.setParent(null);
		}
		return super.beforeAdd();
	}


	@Override
	protected boolean beforeUpdate() {
		if(entity.getParent()!=null && Validators.isEmpty(entity.getParent().getId())){
			entity.setParent(null);
		}
		return super.beforeUpdate();
	}


	@Override
	protected void afterAdd() {
		//logger.logger(getText(LOG_FUNC_ADD, new String[]{entity.getName()}), "");
	}

	/**
	 * 目前删除时如果要做日志，必须重写该方法，并且从数据库中查出对应的描述字段
	 */
	public void doDelete() {
		StringBuilder sb = new StringBuilder();
		for (String str : deletes.split(";")) {
			CoreAuthFunc func = defaultService.get(str, CoreAuthFunc.class);
			if(func!=null){
				defaultService.delete(func);
				sb.append(func.getName()).append(",");
			}
		}
		//logger.logger(getText(LOG_FUNC_DELETE,new String[]{sb.toString()}),"");
	}


	@Override
	protected void afterUpdate() {
		//logger.logger(getText(LOG_FUNC_UPDATE, new String[]{entity.getName()}), "");
	}


	public void setAuthManager(AuthManager authManager) {
		this.authManager = authManager;
	}


	public List<CoreAuthFunc> getFuncs() {
		return funcs;
	}
	
	public CoreAuthFunc getEntity() {
		return entity;
	}

	public void setEntity(CoreAuthFunc entity) {
		this.entity = entity;
	}

	public List<CoreAuthModel> getModels() {
		return models;
	}

	public CoreAuthModel getModel() {
		return model;
	}


	public void setModel(CoreAuthModel model) {
		this.model = model;
	}

	private class FuncEasyUITreeConverter extends EasyUITreeConverter{

		public void setExtraValue(EasyUITreeEntity entity,
				TreeStructure treeTarget) {
			entity.getAttributes().put("url", ((CoreAuthFunc) treeTarget).getUrl());
			entity.getAttributes().put("operations", ((CoreAuthFunc) treeTarget).getOperations());
			entity.getAttributes().put("sort", ((CoreAuthFunc) treeTarget).getSort());
			entity.getAttributes().put("durable", ((CoreAuthFunc) treeTarget).getDurable());
			entity.getAttributes().put("priority", ((CoreAuthFunc) treeTarget).getPriority());
			entity.getAttributes().put("disabled", ((CoreAuthFunc) treeTarget).isDisabled());
			entity.getAttributes().put("isOper", ((CoreAuthFunc) treeTarget).getIsOper());
			entity.setState(EasyUITreeEntity.STATE_OPEN);
		}

	}
	
	public static class CoreAuthFuncVo implements BaseVojo<String>,TransObject{ 
		private String id;
		private String name;
		private Integer sort;
		private String url;
		private String operations;
		private CoreAuthFuncVo parent;
		private Boolean isMenu;
		private String icon;
		private Integer durable;
		private CoreAuthModel model;
		private boolean disabled;
		private int priority; 

		private String define;
		private boolean isOper;
		private String scope;
		
		@Override
		public String getId() {
			return id;
		}
		@Override
		public void setId(String id) {
			this.id = (String) id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Integer getSort() {
			return sort;
		}
		public void setSort(Integer sort) {
			this.sort = sort;
		}
		public String getUrl() {
			return url;
		}
		public void setUrl(String url) {
			this.url = url;
		}
		public String getOperations() {
			return operations;
		}
		public void setOperations(String operations) {
			this.operations = operations;
		}
		
		public CoreAuthFuncVo getParent() {
			return parent;
		}
		public void setParent(CoreAuthFuncVo parent) {
			this.parent = parent;
		}
		public Boolean getIsMenu() {
			return isMenu;
		}
		public void setIsMenu(Boolean isMenu) {
			this.isMenu = isMenu;
		}
		public String getIcon() {
			return icon;
		}
		public void setIcon(String icon) {
			this.icon = icon;
		}
		public Integer getDurable() {
			return durable;
		}
		public void setDurable(Integer durable) {
			this.durable = durable;
		}
		public CoreAuthModel getModel() {
			return model;
		}
		public void setModel(CoreAuthModel model) {
			this.model = model;
		}
		public boolean isDisabled() {
			return disabled;
		}
		public void setDisabled(boolean disabled) {
			this.disabled = disabled;
		}
		public int getPriority() {
			return priority;
		}
		public void setPriority(int priority) {
			this.priority = priority;
		}
		public String getDefine() {
			return define;
		}
		public void setDefine(String define) {
			this.define = define;
		}
		public boolean getIsOper() {
			return isOper;
		}
		public void setIsOper(boolean isOper) {
			this.isOper = isOper;
		}
		public String getScope() {
			return scope;
		}
		public void setScope(String scope) {
			this.scope = scope;
		}
		
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public int getPriority() {
		return priority;
	}

	public void setPriority(int priority) {
		this.priority = priority;
	}

/*	@Override
	public Logger getLogger() {
		return logger;
	}*/
}
